/**
 * 参数验证中间件
 */

/**
 * 验证分页参数
 */
function validatePaginationParams(req, res, next) {
  const { page, limit } = req.query

  // 设置默认值
  const pageNum = page ? parseInt(page) : 1
  const limitNum = limit ? parseInt(limit) : 10

  // 验证页码参数
  if (isNaN(pageNum) || pageNum < 1) {
    return res.status(400).json({
      code: 400,
      message: '页码参数(page)必须大于0',
      data: null,
      errors: [
        {
          field: 'page',
          message: '页码参数必须大于0',
          value: page,
        },
      ],
      timestamp: new Date().toISOString(),
    })
  }

  // 验证每页条数参数
  if (isNaN(limitNum) || limitNum < 1 || limitNum > 100) {
    return res.status(400).json({
      code: 400,
      message: '每页条数参数(limit)必须在1-100之间',
      data: null,
      errors: [
        {
          field: 'limit',
          message: '每页条数参数必须在1-100之间',
          value: limit,
        },
      ],
      timestamp: new Date().toISOString(),
    })
  }

  // 将验证后的参数添加到请求对象
  req.pagination = {
    page: pageNum,
    limit: limitNum,
  }

  next()
}

/**
 * 验证搜索参数
 */
function validateSearchParams(req, res, next) {
  const { q } = req.query

  if (!q || q.trim() === '') {
    return res.status(400).json({
      code: 400,
      message: '搜索关键词(q)是必传参数',
      data: null,
      errors: [
        {
          field: 'q',
          message: '搜索关键词是必传参数',
          value: q,
        },
      ],
      timestamp: new Date().toISOString(),
    })
  }

  next()
}

/**
 * 解析排序参数
 */
function parseSortParams(req, res, next) {
  const { sort } = req.query

  if (sort) {
    try {
      let sortArray = []

      if (Array.isArray(sort)) {
        // 数组格式：[{field: 'publishDate', order: 'desc'}, ...]
        sortArray = sort
          .map((item) => {
            if (typeof item === 'object' && item.field && item.order) {
              return {
                field: item.field,
                order: item.order === 'asc' ? 'asc' : 'desc',
              }
            }
            return null
          })
          .filter(Boolean)
      } else if (typeof sort === 'string') {
        // 字符串格式：'publishDate:desc,viewCount:desc'
        sortArray = sort.split(',').map((item) => {
          const [field, order = 'desc'] = item.split(':')
          return {
            field: field.trim(),
            order: order.trim() === 'asc' ? 'asc' : 'desc',
          }
        })
      }

      req.sort = sortArray
    } catch (error) {
      console.warn('排序参数解析失败:', error)
      req.sort = []
    }
  }

  next()
}

/**
 * 解析过滤参数
 */
function parseFilterParams(req, res, next) {
  const filters = {}

  // 处理多值参数
  const multiValueFields = ['status', 'category', 'tag', 'author']

  multiValueFields.forEach((field) => {
    const value = req.query[field]
    if (value) {
      if (Array.isArray(value)) {
        filters[field] = value
      } else if (typeof value === 'string') {
        filters[field] = value.includes(',') ? value.split(',') : [value]
      }
    }
  })

  // 处理布尔值参数
  if (req.query.featured !== undefined) {
    filters.featured = req.query.featured === 'true' || req.query.featured === true
  }

  // 处理日期范围参数
  if (req.query.dateRange) {
    try {
      const dateRange =
        typeof req.query.dateRange === 'string'
          ? JSON.parse(req.query.dateRange)
          : req.query.dateRange

      if (dateRange.start && dateRange.end) {
        filters.dateRange = {
          start: dateRange.start,
          end: dateRange.end,
        }
      }
    } catch (error) {
      console.warn('日期范围参数解析失败:', error)
    }
  }

  // 处理数值范围参数
  const rangeFields = ['viewCount', 'readTime']
  rangeFields.forEach((field) => {
    const rangeValue = req.query[field]
    if (rangeValue) {
      try {
        const range = typeof rangeValue === 'string' ? JSON.parse(rangeValue) : rangeValue

        if (range && (range.min !== undefined || range.max !== undefined)) {
          filters[field] = {
            min: range.min ? parseInt(range.min) : undefined,
            max: range.max ? parseInt(range.max) : undefined,
          }
        }
      } catch (error) {
        console.warn(`${field}范围参数解析失败:`, error)
      }
    }
  })

  // 处理搜索字段参数
  if (req.query.searchFields) {
    const searchFields = Array.isArray(req.query.searchFields)
      ? req.query.searchFields
      : req.query.searchFields.split(',')
    filters.searchFields = searchFields.map((field) => field.trim())
  }

  req.filters = filters
  next()
}

/**
 * 组合验证中间件
 */
function validateListParams(req, res, next) {
  validatePaginationParams(req, res, (err) => {
    if (err) return next(err)

    parseSortParams(req, res, (err) => {
      if (err) return next(err)

      parseFilterParams(req, res, next)
    })
  })
}

/**
 * 组合搜索验证中间件
 */
function validateSearchListParams(req, res, next) {
  validateSearchParams(req, res, (err) => {
    if (err) return next(err)

    validateListParams(req, res, next)
  })
}

module.exports = {
  validatePaginationParams,
  validateSearchParams,
  parseSortParams,
  parseFilterParams,
  validateListParams,
  validateSearchListParams,
}
